<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="940px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建数据字典" : "编辑数据字典" }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleCancel"></span>
      </div>
    </div>

    <el-form class="pl30 pr30" :model="formData" ref="form" label-width="100px">
      <el-form-item
        label="类型"
        prop="type"
        :rules="[
          {
            required: true,
            message: '请选择或输入字典类型',
            trigger: 'change',
          },
          { max: 50, message: '字典类型最大长度为50' },
        ]"
      >
        <template slot="label"
          >字典类型
          <el-tooltip
            popper-class="custom-popper"
            content="字典类型可以通过输入来创建,最大长度为50"
            placement="top"
          >
            <i class="el-icon-question" />
          </el-tooltip>
        </template>

        <el-select
          v-model="formData.type"
          style="width: 560px"
          :disabled="!isNew"
          class="mr10"
          filterable
          allow-create
          :loading="typeLoading"
          placeholder="请选择或输入字典类型"
        >
          <el-option
            v-for="(item, index) in typeList"
            :key="index"
            :value="item"
            :label="item"
          />
        </el-select>
        <el-button type="text" style="margin-bottom: 10px" @click="addItem"
          >新增文本</el-button
        >
      </el-form-item>

      <draggable
        v-model="formData.options"
        chosen-class="chosen"
        force-fallback="true"
        group="people"
        animation="300"
        handle=".mover"
      >
        <div
          style="display: flex"
          v-for="(item, index) in formData.options"
          :key="index"
        >
          <el-form-item
            label="文本"
            :prop="'options.' + index + '.optionName'"
            :rules="[
              {
                required: true,
                message: '字典文本不能为空',
                trigger: 'change',
              },
            ]"
          >
            <el-input
              v-model="item.optionName"
              style="width: 250px; margin-right: 20px"
              placeholder="请输入字典文本"
              :maxlength="50"
              show-word-limit
            />
          </el-form-item>
          <el-form-item
            label="值"
            label-width="40px"
            :prop="'options.' + index + '.optionValue'"
            :rules="[
              {
                required: true,
                message: '字典值不能为空',
                trigger: 'change',
              },
              {
                pattern: DICT_OPTION_VALUE_REG.pattern,
                message: DICT_OPTION_VALUE_REG.message,
                trigger: 'change',
              },
            ]"
          >
            <el-input
              v-model="item.optionValue"
              style="width: 250px; margin-right: 20px"
              placeholder="请输入字典值"
              :maxlength="50"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label-width="10px">
            <!-- v-if="formData.options.length > 0 && isNew" -->
            <el-button
              type="text"
              @click="deleteItem(item, index)"
            >
              <i class="el-icon-delete" />
            </el-button>
          </el-form-item>

          <el-form-item label-width="10px">
            <GlobalizationConfigWord
              :localism="formData.options[index].localism"
              @setLangCode="setLangCode($event, index)"
            />
          </el-form-item>

          <el-form-item label-width="10px">
            <i class="mover el-icon-rank iconcolor poi"></i>
          </el-form-item>
        </div>
      </draggable>
    </el-form>

    <div slot="footer" class="tr">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button :loading="confirmLoading" type="primary" @click="submit"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import draggable from "vuedraggable";
import GlobalizationConfigWord from "@/components/globalizationConfigWord.vue";
import {
  getHmdictionaryTypelist,
  postHmdictionary,
  getHmdictionaryOptions,
} from "@/apis/paas/HmDictionaryController.js";
import { DICT_OPTION_VALUE_REG } from "@/utils/reg";

export default {
  name: "DictForm",
  components: {
    draggable,
    GlobalizationConfigWord,
  },
  data() {
    return {
      showVisible: false,
      confirmLoading: false,
      DICT_OPTION_VALUE_REG,
      formData: {
        options: [
          {
            optionName: "",
            optionValue: "",
            localism: "",
          },
        ],
      },
      typeList: [],
      typeLoading: false,
    };
  },

  computed: {
    isNew() {
      return !this.formData.id;
    },
  },

  watch: {
    async "formData.type"(val) {
      if (!val) return;
      const res = await getHmdictionaryOptions({ type: val });
      this.formData.options = res?.length
        ? res
        : [
            {
              optionName: "",
              optionValue: "",
              localism: "",
            },
          ];
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
  },

  created() {},

  methods: {
    setLangCode(props, index) {
      this.formData.options[index].localism = props;
    },
    async addForm() {
      this.typeList = await getHmdictionaryTypelist();
      this.formData = {
        options: [
          {
            optionName: "",
            optionValue: "",
            localism: "",
          },
        ],
      };
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    async editForm(record = {}) {
      this.typeList = await getHmdictionaryTypelist();
      const res = await getHmdictionaryOptions({ type: record.type });
      this.formData = {
        id: record.id,
        type: record.type,
        options: res,
      };
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    async submit() {
      try {
        await this.$refs.form.validate();
        const { id, options, type } = this.formData;
        let params = {};
        params.type = type;
        params.options = options.map((item, index) => {
          return {
            id: item.id || undefined,
            localism: item.localism,
            optionName: item.optionName,
            optionValue: item.optionValue,
            serialNum: index + 1,
          };
        });

        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key];
        }
        this.confirmLoading = true;
        postHmdictionary(params)
          .then((res) => {
            this.handleCancel();
            this.$emit("ok");
          })
          .finally(() => {
            this.confirmLoading = false;
          });
      } catch (error) {
        console.log(error);
      }
    },
    handleCancel() {
      this.showVisible = false;
      this.formData.options = [
        {
          optionName: "",
          optionValue: "",
          localism: "",
        },
      ];
      this.typeList = [];
    },
    deleteItem(item, index) {
      this.formData.options.splice(index, 1);
    },
    addItem() {
      this.formData.options.push({
        optionName: "",
        optionValue: "",
        localism: "",
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
